import { queryProblemPage, queryProblemInfoById, updateProblem } from './problemService';
import { queryDictList } from '@/services/dict';
import { routerRedux } from 'dva/router';
import { DICT } from './enum';

export default {
  namespace: 'report_template_question',

  state: {
    list: { data: [] },
    details: [],
    cond: {},
    dict: {}
  },

  effects: {
    *initCond(_, { put }) {
      yield put({ type: 'setCond', payload: {checkType: '2'} });
      yield put({ type: 'queryPage' })
    },
    *updateCond({ payload }, { put }) {
      const { pageSize, pageNum, ...cond } = payload;
      yield put({ type: 'setCond', payload: cond });
      yield put({ type: 'queryPage', payload })
    },
    *queryPage({ payload = { pageNum: 1, pageSize: 10 } }, { call, put, select }) {
      const cond = yield select(state => state.report_template_question.cond);
      const params = { ...payload, ...cond };
      const { list = [], total } = yield call(queryProblemPage, params);
      yield put({ type: 'queryDict', payload: {keyList: DICT} });
      yield put({ type: 'queryDictList' });
      yield put({ type: 'setPage', payload: { list, total } })
    },
    *queryDict({ payload }, { call, put }) {
      const dict = yield call(queryDictList, payload);
      yield put({ type: 'setDict', payload: dict })
    },
    *queryInfoById({ payload }, { call, put }) {
      const response = yield call(queryProblemInfoById, payload);
      yield put({ type: 'setInfo', payload: response })
    },
    *queryEditInfoById({ payload }, { call, put }) {
      const response = yield call(queryProblemInfoById, payload.id);
      const items = {};
      payload.keys.forEach(item => {
        items[item] = response[item]
      });
      yield put({ type: 'setEditInfo', payload: items })
    },
    *update({ payload }, { call, put }) {
      yield call(updateProblem, payload);
      yield put(routerRedux.push('/data/report_template_question'));
    }
  },

  reducers: {
    setCond(state, action) {
      return {
        ...state,
        cond: action.payload
      }
    },
    setPage(state, action) {
      return {
        ...state,
        list: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    },
    setDict(state, action) {
      return {
        ...state,
        dict: action.payload
      }
    },
    setInfo(state, action) {
      return {
        ...state,
        details: action.payload
      }
    },
    setEditInfo(state, action) {
      return {
        ...state,
        editDetails: action.payload
      }
    }
  }
}
